package com.neu.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.base.Result;
import com.neu.entity.FpFatherDemand;
import com.neu.entity.FpSecondDemand;
import com.neu.entity.Task;
import com.neu.entity.dto.DemandDTO;
import com.neu.mapper.FpFatherDemandMapper;
import com.neu.mapper.FpSecondDemandMapper;
import com.neu.service.FpFatherDemandService;
import com.neu.service.FpSecondDemandService;
import com.neu.service.TaskService;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class FpSecondDemandServiceImpl extends ServiceImpl<FpSecondDemandMapper, FpSecondDemand> implements FpSecondDemandService {

    @Autowired
    private FpFatherDemandService fpFatherDemandService;

    @Autowired
    TaskService taskService;

    @Autowired
    private FpFatherDemandMapper fpFatherDemandMapper;
    @Autowired
    private FpSecondDemandMapper fpSecondDemandMapper;

    @Override
    public List<DemandDTO> listDemand() {
//        // 使用lambdaQuery查询所有子级需求
//        List<FpSecondDemand> secondDemandList = this.lambdaQuery().list();

        // 使用 lambdaQuery 查询所有子级需求并按 fid 升序排序
        List<FpSecondDemand> secondDemandList = this.lambdaQuery()
                .orderByAsc(FpSecondDemand::getFid)
                .list();
        // 对每个子级需求进行转换
        List<DemandDTO> childdemandDTOList = secondDemandList.stream()
                .map(secondDemand -> {
                    // 获取父需求信息
                    FpFatherDemand fatherDemand = fpFatherDemandService.getById(secondDemand.getFid());

                    // 将子级需求和父级需求数据封装到DemandDTO
                    return new DemandDTO(
                            secondDemand.getSid(),
                            secondDemand.getFid(),
                            fatherDemand != null ? fatherDemand.getPname() : null, // 父需求名称
                            secondDemand.getSname(),
                            secondDemand.getDescription(),
                            secondDemand.getType(),
                            secondDemand.getUfp(),
                            secondDemand.getDegree()
                    );
                })
                .collect(Collectors.toList());
        return childdemandDTOList;
    }

    @Override
    public boolean save(FpSecondDemand entity) {
        // 调用父类的保存方法
        boolean isSaved = super.save(entity);
        // 保存后按需查询排序（不改变存储，仅影响查询的表现）
        if (isSaved) {
            // 手动触发排序查询逻辑或事件监听
            this.lambdaQuery().orderByAsc(FpSecondDemand::getFid).list();
        }
        return isSaved;
    }

    @Transactional // 添加事务支持
    @Override
    public boolean addWithParent(DemandDTO demandDTO) {
        // 1. 新增父级需求
        FpFatherDemand fatherDemand = new FpFatherDemand();
        fatherDemand.setPname(demandDTO.getPname());
        boolean isParentSaved = fpFatherDemandService.save(fatherDemand);

        if (!isParentSaved) {
            throw new RuntimeException("父级需求保存失败");
        }

        // 2. 新增子级需求
        FpSecondDemand secondDemand = new FpSecondDemand();
        secondDemand.setFid(fatherDemand.getId()); // 使用父级需求 ID
        secondDemand.setSname(demandDTO.getSname());
        secondDemand.setDescription(demandDTO.getDescription());
        secondDemand.setType(demandDTO.getType());
        secondDemand.setUfp(demandDTO.getUfp());
        secondDemand.setDegree(demandDTO.getDegree());
        boolean isChildSaved = this.save(secondDemand);

        System.out.printf("ID为：", fatherDemand.getId());
        System.out.printf("FID为：", secondDemand.getFid());
        if (!isChildSaved) {
            throw new RuntimeException("子级需求保存失败");
        }

        return true;
    }

    @Override
    public List<DemandDTO> listByTaskId(String taskid) {
        List<DemandDTO> demands = new ArrayList<DemandDTO>();
        LambdaQueryWrapper<FpFatherDemand> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(FpFatherDemand::getTaskId, taskid);
        List<FpFatherDemand> fatherDemands = this.fpFatherDemandMapper.selectList(queryWrapper1);

        for (FpFatherDemand fatherDemand : fatherDemands) {
            Integer fid = fatherDemand.getId();
            LambdaQueryWrapper<FpSecondDemand> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FpSecondDemand::getFid, fid);
            List<FpSecondDemand> secDemands = this.fpSecondDemandMapper.selectList(queryWrapper2);
            if(secDemands.isEmpty()){
                DemandDTO demandDTO = new DemandDTO();
                demandDTO.setFid(fatherDemand.getId());
                demandDTO.setPname(fatherDemand.getPname());
                demands.add(demandDTO);
                continue;
            }
            for (FpSecondDemand secondDemand : secDemands) {
                demands.add(new DemandDTO(
                        secondDemand.getSid(),
                        secondDemand.getFid(),
                        fatherDemand.getPname(), // 父需求名称
                        secondDemand.getSname(),
                        secondDemand.getDescription(),
                        secondDemand.getType(),
                        secondDemand.getUfp(),
                        secondDemand.getDegree()
                ));
            }
        }

        return demands;
    }

    @Override
    public Result cauclTotalUfp(String taskId) {
        LambdaQueryWrapper<FpFatherDemand> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(FpFatherDemand::getTaskId, taskId);
        List<FpFatherDemand> fatherDemands = this.fpFatherDemandMapper.selectList(queryWrapper1);
        List<Integer> fids = fatherDemands.stream().map(FpFatherDemand::getId).collect(Collectors.toList());

        LambdaQueryWrapper<FpSecondDemand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(FpSecondDemand::getFid, fids);
        List<FpSecondDemand> secDemands = this.fpSecondDemandMapper.selectList(queryWrapper);
        //直接求和
        Integer totalUfp = secDemands.stream().map(FpSecondDemand::getUfp).reduce(0, Integer::sum);
        /*//按照需求类型分类
        Map<String, List<FpSecondDemand>> typeMap = secDemands.stream().collect(Collectors.groupingBy(FpSecondDemand::getType));
        //计算每个需求类型的ufp总和
        Map<String, Integer> ufpMap = new HashMap<>();
        for (Map.Entry<String, List<FpSecondDemand>> entry : typeMap.entrySet()) {
            Integer ufp = entry.getValue().stream().map(FpSecondDemand::getUfp).reduce(0, Integer::sum);
            ufpMap.put(entry.getKey(), ufp);
        }*/
        return Result.success(totalUfp);
    }

    @Override
    public List<Task> allForFp() {
        return taskService.allForFp();
    }


}
